﻿using BPMS.Core.DataAccess;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace BPMS.Core.Builders
{
    public class DbParameterFactory
    {
        public static readonly DbParameterFactory Instance = new DbParameterFactory();

        private DbParameterFactory()
        {

        }
        /// <summary>
        /// 输入参数
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public IEnumerable<DbParameterWrapper> InParameters(object obj)
        {
            if (obj == null || obj == DBNull.Value)
            {
                return new List<DbParameterWrapper>();
            }
            return DataStructureCache.GetPropertyList(obj.GetType()).Select(item =>
            {
                return new DbParameterWrapper(
                "@" + item.Name,
                item.GetValue(obj, null) ?? DBNull.Value,
                ParameterDirection.Input);
            });
        }
        /// <summary>
        /// 输出参数
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public IEnumerable<DbParameterWrapper> OutParameters(object obj)
        {
            if (obj == null || obj == DBNull.Value)
            {
                return new List<DbParameterWrapper>();
            }
            return DataStructureCache.GetPropertyList(obj.GetType()).Select(item =>
            {
                return new DbParameterWrapper(
                "@Out_" + item.Name,
                item.GetValue(obj, null) ?? DBNull.Value,
                ParameterDirection.Output);
            });
        }
        /// <summary>
        /// 主键输入参数
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public IEnumerable<DbParameterWrapper> KeyParameters(object obj)
        {
            return DataStructureCache.GetKeyPropertyList(obj.GetType()).Select(item =>
            {
                return new DbParameterWrapper(
                "@" + item.Name,
                item.GetValue(obj, null) ?? DBNull.Value,
                ParameterDirection.Input);
            });
        }
        /// <summary>
        /// 分页查询参数
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public IEnumerable<DbParameterWrapper> PageParameters(int pageIndex, int pageSize, object obj)
        {
            return InParameters(obj).Union(new DbParameterWrapper[]{ 
                                                      new DbParameterWrapper("@PageIndex", pageIndex), 
                                                      new DbParameterWrapper("@PageSize", pageSize)
                                                  });
        }
    }
}
